<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\property\bill;

use think\facade\Db;
use app\common\repositories\BaseRepository;
use app\common\model\energy\EnergyBillModel;
use app\common\dao\property\bill\PropertyBillMonthDao;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class PropertyBillMonthRepository
 *
 * @mixin PropertyBillMonthDao
 */
class PropertyBillMonthRepository extends BaseRepository
{

    public function __construct(PropertyBillMonthDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }


    public function addInfo(array $data, int $propertyId, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $billInfo = $this->dao->create($data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'PROPERTY.BILL.MONTH.ADD', $data);
            return $billInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PROPERTY.BILL.MONTH.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->where('id', $id)
            ->find();
        return $data;
    }


    public function batchDelete(array $ids, int $userId = 0, string $remark = '')
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ], 'id,property_id,month_time');
        if ($list) {
            $num = 0;
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId, $remark);
                $num++;
            }
            return $num;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0, string $remark = '')
    {
        return Db::transaction(function () use ($info, $userId, $remark) {
            ## 账单删除事件
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PROPERTY.BILL.MONTH.DEL', $info, $remark);
            $this->dao->delete($info['id']);
        });
    }

    /**
     * 任务生成 宿舍月账单
     * @param $contractInfo
     * @param $billInfo
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-04 12:37
     */
    public function taskPropertyBillInfo(int $propertyid)
    {
        $monthTime = date('Y-m');

        ## 物业月度账单列表
        $billInfo = $this->getSearch([])
            ->where('month_time', $monthTime)
            ->where('property_id', $propertyid)
            ->find();
        if (!$billInfo && count($billInfo) <= 0) {
            $data['month_time'] = $monthTime;
            $data['closed_energy'] = $this->getEnergyAmount($propertyid, $monthTime); ## 水电气汇总
            $this->dao->create($data);
        }
    }

    /**
     * 根据物业 ID 与月份 查询 水电气费用汇总
     * @param int $propertyid
     * @param $monthTime
     * @return float
     *
     * @author Amos
     * 2024-05-04 14:21
     */
    public function getEnergyAmount(int $propertyid, $monthTime, $energyType = null)
    {
        return EnergyBillModel::where('property_id', $propertyid)
            ->when($energyType !== null, function ($query) use ($energyType) {
                $query->where('energy_type', $energyType);
            })
            ->where('month_time', $monthTime)
            ->sum(\think\facade\Db::raw('basic_amount+service_amount+loss_amount'));
    }


}